<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div style="width: 100%;">
    <div style="width: 100%;">
      <div style="display: flex; padding: 1px 15px;align-items: center;">
        <!-- 组件1 : 新增按钮 + 菜单名称 -->
        <el-button type="primary" @click="add">新建</el-button>
        <span style="margin-left: 10px; font-size: 20px;">员工</span>
        <div style="margin-left: auto;margin-right: auto;" class="search-operation-container">
          <!-- 搜索框 -->
          <ISearch :fieldsConfig="searchDataConfig || []" @searchCallBack="searchCallBack"
            v-if="multipleSelection.length == 0"></ISearch>
          <!-- 操作按钮组 -->
          <div v-else>
            <el-button type="primary" style="background-color: #f1edf0; color: #714B67;">
              {{ "(" + multipleSelection.length + ") 已选取" }}
            </el-button>
            <el-dropdown trigger="click" popper-class="operation-dropdown" @command="handleOperationCommand">
              <el-button type="primary">
                <el-icon>
                  <Tools />
                </el-icon> 操作 <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="delete">删除</el-dropdown-item>
                  <el-dropdown-item command="export">导出</el-dropdown-item>
                  <el-dropdown-item command="archive">归档</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        <!-- 按钮组-->
        <IdooButtonGroup :buttonConfigs="buttonGroupDatas" @clickCallBack="buttonGroupChange" is-active-style />
      </div>
    </div>
    <!-- 分割线 -->
    <el-divider border-style="dotted" />

    <div style="display: flex; height: 100vh;">
      <!-- 部门树 -->
      <div class="main-left-area">
        <div style="padding: 15px">
          <el-icon>
            <Avatar />
          </el-icon>
          <span style="font-size: 15px; font-weight: 600;"> 部门 </span>
        </div>
        <el-tree :data="deptTreeData" :expand-on-click-node="false" :props="defaultProps" node-key="id"
          @node-click="treeClick">
          <template #default="{ data }">

            <span class="tree-node-title" :title="data.label"> {{ data.label }} </span>
            <span> {{ data.biz_count }} </span>
          </template>
        </el-tree>
      </div>
      <!-- 表格列表 -->
      <div style="display: flex;flex-direction: column; height: auto;position: relative; width: 100%;flex: 1;">
        <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange"
          v-if="showType == 'list'">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="员工姓名" width="180" />
          <el-table-column prop="titleName" label="头衔" sortable width="180" />
          <el-table-column prop="phone" label="电话号码" width="180" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="jobAddress" label="工作地址" width="180" />
          <el-table-column prop="job" label="工作岗位" width="180" />
          <el-table-column prop="manager" label="直属领导" width="180" />
          <el-table-column prop="assensmentDate" label="最近考核日期" width="180" />
        </el-table>
        <!-- 卡片列表 -->
        <div class="card-list-container" v-if="showType == 'card'" ref="cardListContainer" @scroll="handleCardScroll">
          <div style="display: flex; flex-wrap: wrap; gap: 10px;">
            <div v-for="cardItem in displayedCards" :key="cardItem.id" class="card">
              <el-card>
                <div class="card-content">
                  <div class="avatar-container" style="float: left;">
                    <UserAvatar :avatar-data="cardItem.userAvatars" />
                    <div class="avatar-tooltip">
                      <UserAvatar style="z-index: 1000;" :avatar-data="cardItem.userAvatars" />
                    </div>
                  </div>
                  <div>
                    <span>员工姓名：{{ cardItem.name }} ;</span>
                    <span>员工姓名：{{ cardItem.name }} ;</span>
                    <span>员工姓名：{{ cardItem.name }} ;</span>
                    <span>员工姓名：{{ cardItem.name }} ;</span>
                  </div>
                </div>
              </el-card>
            </div>
          </div>
          <div v-if="displayCount < cardData.length" class="load-prompt">向下滑加载</div>
        </div>
        <!-- 分页 -->
        <div style="margin-top: 20px;">
          <IdooPagination :param="initPaginationParam" style="float:right ;margin-right: 25px;"
            @click-call-back="paginationCallBack"></IdooPagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import UserAvatar from '@/components/base/profile/userAvatar/index.vue'
import { onMounted, ref, computed } from 'vue';
import { useRoute } from 'vue-router';
import IdooPagination from '@/components/base/pagination/index.vue'
import { Tools, Avatar } from '@element-plus/icons-vue'
import ISearch from '@/components/base/search/index.vue'
import { tableDatatTest, deptTree, buttonGroupData } from './testData';
import IdooButtonGroup from '@/components/base/button/buttonGroup/index.vue';
import type { ButtonGroupStructure } from '@/components/base/button/buttonGroup';
import type { PaginationStructure } from '@/components/base/pagination';
import type { SearchDataStruct } from '@/components/base/search';
import router from '@/router';
//展示方式  list\card
const showType = ref<string>('list')
//列表勾选得内容
const multipleSelection = ref<[]>([]);
//部门树数据
const deptTreeData = deptTree;
//按钮组数据
const buttonGroupDatas = buttonGroupData;
//搜索框参数
const searchDataConfig = ref<Array<SearchDataStruct>>();
//分页参数
const initPaginationParam = ref<PaginationStructure>();
const defaultProps = {
  children: 'children',
  label: 'label',
  id: 'id',
}
//表格勾选
const handleSelectionChange = (val: []) => {
  console.log(val);
  multipleSelection.value = val
}
const tableData = tableDatatTest
const cardData = ref([]);
// Lazy load：默认显示 6 行，每行 6 个（即 36 个）
const displayCount = ref(6 * 6);
const displayedCards = computed(() => cardData.value.slice(0, displayCount.value));
// 滚动容器引用
const cardListContainer = ref<HTMLElement | null>(null);

const treeClick = (val: object) => {
  console.log(val);
}
const paginationCallBack = (obj: object) => {
  console.log(obj);
}

//按钮组回调
const buttonGroupChange = (callbackItem: ButtonGroupStructure) => {
  console.log(callbackItem)
  showType.value = callbackItem.id;
  resetViewData();
}

const resetViewData = () => {
  //清空表格勾选数组
  multipleSelection.value = [];
}
//搜索框回调
const searchCallBack = (callbackItem: object) => {
  console.log("搜索回调", callbackItem)
}

const add = () => {
  router.push({
    path: '/employess-staff/add'
  })
}

onMounted(async () => {
  //获取模块下的菜单数据；
  //获取登录用户信息
  console.warn(2222)
  const $route = useRoute()
  console.log($route)
  console.log($route.params);
  initPaginationParam.value = {
    pageSize: 80,
    totalNum: 235
  }
  //构造搜索框数据
  searchDataConfig.value = [
    {
      field: 'name',
      title: '头衔',
      fieldType: 'string',
    },
    {
      field: 'titleName',
      title: '性别',
      fieldType: 'string',
    },
    {
      field: 'phone',
      title: '电话号码',
      fieldType: 'string',
    },
    {
      field: 'email',
      title: '邮箱',
      fieldType: 'string',
    },
    {
      field: 'jobAddress',
      title: '工作地址',
      fieldType: 'input',
    },
    {
      field: 'job',
      title: '岗位',
      fieldType: 'input',
    },
    {
      field: 'manager',
      title: '直属领导',
      fieldType: 'input',
    },
    {
      field: 'assensmentDate',
      title: '最近考核日期',
      fieldType: 'input',
    },
  ]
  //构造卡片数据
  tableData.map(item => {
    const a = {
      ...item,
      userAvatars: {
        avatar_name: item.name,
        avatar_width: '140',
      }
    }
    cardData.value.push(a);
  });
  // 解除固定显示卡片数量，等待滚动事件加载更多
  // 此处不再使用 IntersectionObserver
});

// 滚动事件处理：当滚动条到底部时加载额外 6 行（6*6=36）数据
function handleCardScroll() {
  if (!cardListContainer.value) return;
  const el = cardListContainer.value;
  if (el.scrollTop + el.clientHeight >= el.scrollHeight - 10) {
    if (displayCount.value < cardData.value.length) {
      displayCount.value += 6 * 6; // 每次加载 5 行数据
    }
  }
}

const handleOperationCommand = (command: string) => {
  console.log("操作命令:", command);
  console.log("选中的数据", multipleSelection.value)
  // 根据不同命令执行相应操作
  if (command === "delete") {
    // TODO: 删除操作逻辑
  } else if (command === "export") {
    // TODO: 导出操作逻辑
  } else if (command === "archive") {
    // TODO: 归档操作逻辑
  }
}
</script>

<style scoped>
:deep(.el-divider--horizontal) {
  margin: 20px 0px 0px !important;
}

.main-left-area {
  border-right: 1px solid #dcdfe6;
  width: 300px;
  min-height: 400px;
  overflow: outo;
}

.card {
  flex-basis: calc(25% - 10px);
  /* 考虑 10px 的间隙，每个卡片占 20% 宽度 */
  height: 150px;
  box-sizing: border-box;
}

:deep(.el-card) {
  overflow: visible !important;
}

:deep(.el-card__body) {
  justify-content: normal !important;
  align-items: normal !important;
  overflow: visible !important;
}

.card-content {
  height: 140px;
  /* 确保卡片内容填充整个卡片 */
  display: flex;
  justify-content: center;
  align-items: center;
  /* 使卡片内容居中显示 */
  overflow: visible;
}

.tree-node-title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  max-width: 100px;
  /* 根据需要调整最大宽度 */
}

.tree-node-title:hover {
  overflow: visible;
  white-space: normal;
  position: relative;
}

.tree-node-title::after {
  content: attr(title);
  position: absolute;
  left: 0;
  top: 100%;
  background: #000;
  color: #fff;
  padding: 5px;
  display: none;
  z-index: 10;
  white-space: nowrap;
  /* 确保提示信息在一行内显示 */
}

.tree-node-title:hover::after {
  display: block;
}

/* 包装头像的容器；相对定位以便提示绝对定位 */
.avatar-container {
  position: relative;
  display: inline-block;
}

/* 隐藏的提示容器，鼠标悬停时显示 */
.avatar-tooltip {
  opacity: 0;
  position: absolute;
  top: 0;
  left: 0;
  /* 使提示覆盖在当前头像上 */
  transform: scale(1.5);
  transform-origin: top left;
  z-index: 1000;
  pointer-events: none;
  /* 防止提示层干扰鼠标事件 */
  transition: opacity 0.3s ease;
}

/* 鼠标悬停时显示提示 */
.avatar-container:hover .avatar-tooltip {
  opacity: 1;
}

.card-list-container {
  max-height: 800px;
  /* 根据实际情况，可以调整到合适的高度显示 5 行卡片 */
  overflow-y: auto;
  position: relative;
  padding-bottom: 30px;
  /* 为加载提示预留空间 */
}

.load-prompt {
  text-align: center;
  padding: 10px;
  background: #f9f9f9;
  color: #888;
  font-size: 14px;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
}

/* 自定义下拉菜单位置：菜单出现在按钮右侧 */
:deep(.operation-dropdown) {
  /* 取消默认定位（建议加 !important 确保覆盖） */
  left: auto !important;
  top: 0 !important;
  transform: translate(100%, 0) !important;
  /* 可根据需要调整偏移量 */
  margin: 0 !important;
}

/* 使下拉菜单宽度与操作按钮宽度一致 */
:deep(.operation-dropdown .el-dropdown-menu) {
  width: auto !important;
  min-width: 100% !important;
  box-sizing: border-box;
}

.search-operation-container {
  height: 32px;
  display: flex;
  align-items: center;
}
</style>
